package com.myproject.cas;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class UnsafeTestKlass {

    private int value;

    public UnsafeTestKlass() {
        this(99);
    }

    public UnsafeTestKlass(int value) {
        this.value = value;
    }


    public int value() {
        return value;
    }


    public static Unsafe getUnsafe() throws Throwable {

        Class<?> unsafeClass = Unsafe.class;

        for (Field f : unsafeClass.getDeclaredFields()) {
            if ("theUnsafe".equals(f.getName())) {
                f.setAccessible(true);
                return (Unsafe) f.get(null);
            }
        }

        throw new IllegalAccessException("no declared field: theUnsafe");

    }

    public static void main(String[] args) throws Throwable {
        Field field = UnsafeTestKlass.class.getDeclaredField("value");
        Unsafe unsafe = getUnsafe();
        long valueOffset = unsafe.objectFieldOffset(field);
        System.out.println("value offset: " + valueOffset);
    }

}
